﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Icoders.MarketTracker.Core.MasterData;
using Icoders.MarketTracker.Core.Repository.MasterDataRepositories;
using Icoders.MarketTracker.Core.Validation;
using Icoders.MarketTracker.Web.Lib;
using Icoders.MarketTracker.Web.Lib.Security;
using Icoders.MarketTracker.Web.Lib.Util;
using Icoders.MarketTracker.Web.Lib.Validation;

namespace Icoders.MarketTracker.Web.Areas.Mobile.Controllers
{
    
    public class MAccountController : Controller{
        //
        // GET: /Mobile/MAccount/
        private IUserRepository _userRepository;
        private IClientRepository _clientRepository;
        private IAreaRepository _areaRepository;
        private IFrsAssignRepository _fsrAssignRepository;
        private IAuditTrailRepository _auditTrailRepository;

        public MAccountController(IUserRepository userRepository, IClientRepository clientRepository, IAreaRepository areaRepository, IFrsAssignRepository fsrAssignRepository, IAuditTrailRepository auditTrailRepository)
        {
            _userRepository = userRepository;
            _clientRepository = clientRepository;
            _areaRepository = areaRepository;
            _fsrAssignRepository = fsrAssignRepository;
            _auditTrailRepository = auditTrailRepository;
        }

        public ActionResult Login()
        {
            return View(new LoginModel());
        }
        [HttpPost]
        public ActionResult Login(LoginModel login, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                CodersEncrypt passEncrypt = new CodersEncrypt();
                if (_userRepository.IsLoginMobile(login.Username,passEncrypt.EncryptThings(login.Password)))
                {
                    User user = _userRepository.GetByUsername(login.Username);
                    

                    FormsAuthentication.SetAuthCookie(login.Username, false);
                    if (Request.Browser.IsMobileDevice)
                    {
                        Saveaudit("Login Mobile User", login.Username, ActionType.Login);
                        return RedirectToAction("Index", "MHome", new {area = "Mobile"});
                    }
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        Saveaudit("Failed Login", login.Username, ActionType.FailedLogin);
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        Saveaudit("Login Mobile User", login.Username, ActionType.Login);
                        return RedirectToAction("Index", "MHome");
                    }
                }else
                {
                    ValidationSummary.DisplayValidationResult("Enter valid username and password", ModelState);
                    //ViewBag.error = "Enter valid username and password";
                }

            }
            return View(new LoginModel());
        }
        public ActionResult LogOut()
        {
            Saveaudit("Logout Mobile User", HttpContext.User.Identity.Name, ActionType.Logout);
            FormsAuthentication.SignOut();
            Session.Abandon();

            // clear authentication cookie
            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            cookie1.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie1);

            // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
            HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);

            FormsAuthentication.RedirectToLoginPage();
            return RedirectToAction("login");
        }
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View(new ChangePassword());
        }
        [HttpPost]
        [Authorize]
        public ActionResult ChangePassword(ChangePassword model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                CodersEncrypt passEncrypt = new CodersEncrypt();
                try
                {
                    _userRepository.ChangePassword(HttpContext.User.Identity.Name,
                                                   passEncrypt.EncryptThings(model.OldPassword),
                                                   passEncrypt.EncryptThings(model.Password));
                    Saveaudit("Change Password Mobile User", HttpContext.User.Identity.Name, ActionType.Updated);
                    if (Url.IsLocalUrl(returnUrl))
                        return Redirect(returnUrl);

                }
                catch (DomainValidationException dve)
                {
                    ValidationSummary.DisplayDomainValidationResult(dve, ModelState);
                    return View(model);
                }
            }else
            {
                ValidationSummary.DisplayValidationResult("Enter valid change password details", ModelState);
                return View(model);
            }
            return RedirectToAction("Index", "MHome");

        }
        [Authorize]
        public ActionResult Profile()
        {
            FsrCustomIdentity identity = (FsrCustomIdentity)User.Identity;
            FsrUserProfile p = new FsrUserProfile();
            if(identity!=null)
            {
                var user = _userRepository.GetById(identity.UserID);
                var area = _areaRepository.GetById(identity.Area);
                var client = _clientRepository.GetById(identity.Client);
                p.Area = area != null ? area.Name : "Not Assigned";
                p.FullName = user.FirstName + " " + user.LastName;
                p.PhoneNumber =user!=null?  user.PhoneNumber:"None";
                p.Email =user!=null? user.Email: "None";
                p.Client =client!=null? client.Name: "Not Assigned";
            }


            return View(p);
        }
        public void Saveaudit(string description, string username, ActionType actionType)
        {
            //  private IUserRepository _userRepository;
            //private IAuditTrailRepository _auditTrailRepository;
            // Saveaudit("Changed Password", HttpContext.User.Identity.Name, ActionType.Updated);
            try
            {
                User user = _userRepository.GetByUsername(username);
                AuditTrail auditTrail = new AuditTrail();
                auditTrail.Description = description;
                auditTrail.UserId = user.Id;
                auditTrail.ActionTypeId = Convert.ToInt32(actionType);
                _auditTrailRepository.Save(auditTrail);
            }
            catch (Exception)
            {
                //throw;
            }
        }
    }
}
